package SERVER;



import java.io.IOException;
import java.net.ServerSocket;
import java.util.ArrayList;

/*
@author Miroslaw
 */
public class ServerStart
{
	static GameTable game_server;
	//static PlayerServerThread[] player;
	static ArrayList <PlayerServerThread> player = new ArrayList<PlayerServerThread>();
	public static void main(String [] args)
	{

		int port_number = 0;
		int players_number = 0;
		int chips_number = 0;
		int big_blind = 0;
		int small_blind = 0;
		
		if (args.length!=5)
		{
			System.out.println("To start Server correctly you have to type: java ServerStart port_number players_number chips_number big_blind small_blind");
			System.exit(1);
		}
		else
		{
			try
			{
				port_number = Integer.parseInt(args[0]);
				players_number = Integer.parseInt(args[1]);
				chips_number = Integer.parseInt(args[2]);
				big_blind = Integer.parseInt(args[3]);
				small_blind = Integer.parseInt(args[4]);
			}
			catch (NumberFormatException NFE)
			{
				System.out.println("Typed variables are not int type");
				System.exit(1);
			}
		}
		try 
		{
			ServerSocket Server = new ServerSocket(port_number);
			System.out.println("Started server at port: "+port_number);
			try 
			{
				game_server = new GameTable(players_number, chips_number, big_blind, small_blind);
			}
			catch(BadugiException BE)
			{
				System.out.println(BE.getMessage());
				System.exit(1);
			}
			//player = new ArrayList<PlayerServerThread>();
			int index=0;
			while(true)
			{
				try
				{
					//sprawdzenie czy kazdy z poprzednich elementow tablicy ma przypisany obiekt (jest !=null) i przypisanie mu bieżącego elementu
					System.out.println(GlobalVar.players_connected);
					/*
					player.add(new PlayerServerThread(Server.accept(),GlobalVar.players_connected));
					player.get(GlobalVar.players_connected).start();

					if(player.size()==GlobalVar.players_connected)
					{
						index=GlobalVar.players_connected;
						System.out.println("1+ "+index);
					}
					else
					{
						int j=0;
						while(player.get(j)!=null)
						{
							j++;
						}
						index = j;
						System.out.println(" "+index);
					}*/

					player.add(new PlayerServerThread(Server.accept()));
					player.get(player.size()-1).start();

				}
				catch (IOException e)
				{
					System.out.println("Accept failed");
					System.exit(-1);
				}
			}
		}
		catch(IOException ioe)
		{
			System.out.println("Can't listen at port: "+port_number);
			System.exit(-1);
		}

	}

}
